package com.why.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.why.blog.common.R;
import com.why.blog.common.ResponseCode;
import com.why.blog.common.utils.TimestampUtil;
import com.why.blog.dao.mapper.HaloPostMapper;
import com.why.blog.dao.mapper.HaloPostsTagsMapper;
import com.why.blog.dao.mapper.HaloTagMapper;
import com.why.blog.entity.HaloPost;
import com.why.blog.entity.HaloPostsTags;
import com.why.blog.entity.HaloTag;
import com.why.blog.entity.JwtUser;
import com.why.blog.entity.VO.PostVO;
import com.why.blog.service.PostService;
import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author TriggerWu
 * @since 2019-04-28
 */
@Service
public class HaloPostServiceImpl implements PostService {

    @Autowired
    private HaloPostMapper haloPostMapper;

    @Autowired
    private HaloTagMapper tagMapper;

    @Autowired
    private HaloPostsTagsMapper postsTagsMapper;
    @Autowired
    Mapper beanMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R savePo(PostVO post, JwtUser user) {
        if (StringUtils.isNotBlank(user.getUserId())) {
            post.setUserId(user.getUserId());
        } else {
            return R.getInstance(ResponseCode.USER_NOT_LOGIN.getCode(), ResponseCode.USER_NOT_LOGIN.getMsg());
        }
        HaloPost haloPost = beanMapper.map(post, HaloPost.class);
        //默认允许发言
        haloPost.setPostDate(TimestampUtil.currentTimeStamp());
        haloPost.setPostUpdate(TimestampUtil.currentTimeStamp());
        haloPost.setLogicDel(0);
        haloPost.setPostStatus(0);
        String tagId = null;
        try {
            if (StringUtils.isNotBlank(haloPost.getPostSummary())) {
                tagId = tagId(haloPost.getPostSummary());
                haloPost.setPostSummary(tagId);
            }
            int i = haloPostMapper.insert(haloPost);
            if (i > 0) {
                //return R.getInstance(ResponseCode.RESPONSE_SUCCESS.getCode(), ResponseCode.RESPONSE_SUCCESS.getMsg());
                String[] strings = tagId.split(",");
                for (int j = 0; j < strings.length; j++) {
                    HaloPostsTags pt = new HaloPostsTags();
                    pt.setPostId(haloPost.getPostId())
                            .setTagId(Integer.parseInt(strings[j]));
                    postsTagsMapper.insert(pt);
                }
                return R.getInstance(ResponseCode.RESPONSE_SUCCESS.getCode(), ResponseCode.RESPONSE_SUCCESS.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.getInstance(ResponseCode.ARG_ERROR.getCode(), ResponseCode.ARG_ERROR.getMsg());
    }

    @Override
    public R removePo(String poId) {
        int delete = haloPostMapper.deleteById(poId);
        if (delete > 0) {
            return R.getInstance(ResponseCode.RESPONSE_SUCCESS.getCode(), ResponseCode.RESPONSE_SUCCESS.getMsg());
        }
        return R.getInstance(ResponseCode.ARG_ERROR.getCode(), ResponseCode.ARG_ERROR.getMsg());
    }

    @Override
    public IPage<HaloPost> showList(PostVO postVO, Integer page, Integer pageSize) {
        IPage<HaloPost> ipg = new Page<>(page, pageSize);
        QueryWrapper<HaloPost> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(postVO.getPostId())) {
            wrapper.eq("post_id", postVO.getPostId());
        }
        if (StringUtils.isNotBlank(postVO.getPostTitle())) {
            wrapper.like("post_title", postVO.getPostTitle());
        }
        wrapper.orderByDesc("post_date");
        ipg = haloPostMapper.selectPage(ipg, wrapper);
        return ipg;
    }

    @Override
    public R updatePo(PostVO post) {
        if (post == null || StringUtils.isBlank(post.getUserId())) {
            return R.getInstance(ResponseCode.PARAMETER_ERROR.getCode(), ResponseCode.PARAMETER_ERROR.getMsg());
        }
        HaloPost haloPost = beanMapper.map(post, HaloPost.class);
        haloPost.setPostUpdate(TimestampUtil.currentTimeStamp());
        Integer i = haloPostMapper.updateById(haloPost);
        if (i > 0) {
            return R.getInstance(ResponseCode.RESPONSE_SUCCESS.getCode(), ResponseCode.RESPONSE_SUCCESS.getMsg());
        }
        return R.getInstance(ResponseCode.ARG_ERROR.getCode(), ResponseCode.ARG_ERROR.getMsg());
    }

    @Override
    public R showPostVo(String postId) {
        if (StringUtils.isBlank(postId)) {
            return R.getInstance(ResponseCode.ARG_ERROR.getCode(), ResponseCode.ARG_ERROR.getMsg());
        }
        PostVO postVO = haloPostMapper.showPostVo(postId);
        if (postVO == null) {
            return R.getInstance(ResponseCode.INFO_NO_MORE.getCode(), ResponseCode.INFO_NO_MORE.getMsg());
        }
        return R.getInstance(ResponseCode.RESPONSE_SUCCESS.getCode(), ResponseCode.RESPONSE_SUCCESS.getMsg(), postVO);
    }

    @Override
    public R blogIndex(Integer page, Integer pageSize, Integer categoryId) {
        IPage<PostVO> ipg = new Page<>(page, pageSize);
        List<PostVO> voList = haloPostMapper.RecentIndex(categoryId, (page - 1) * pageSize, pageSize);
        Integer count = haloPostMapper.queryindexCount(categoryId);
        try {
            if (null != voList) {
                ipg.setRecords(voList)
                        .setCurrent(page)
                        .setSize(pageSize)
                        .setPages(count % pageSize == 0 ? count % pageSize : (count % pageSize) + 1)
                        .setTotal(count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.getInstance(ResponseCode.RESPONSE_SUCCESS.getCode(), ResponseCode.RESPONSE_SUCCESS.getMsg(), ipg);
    }

    @Override
    public Integer postRecords(Integer categoryId) {
        if (categoryId <= 0) {
            categoryId = null;
        }
        return haloPostMapper.queryindexCount(categoryId);
    }

    @Override
    public R showCategoryPost(Integer categoryId) {
        if (categoryId == null || categoryId <= 0) {
            return R.getInstance(ResponseCode.ARG_ERROR.getCode(), ResponseCode.ARG_ERROR.getMsg());
        }
        List<PostVO> pvo = haloPostMapper.catePost(categoryId);
        if (pvo.size() == 0 || null == pvo) {
            return R.getInstance(ResponseCode.INFO_NO_MORE.getCode(), ResponseCode.INFO_NO_MORE.getMsg());
        }
        return R.getInstance(ResponseCode.RESPONSE_SUCCESS.getCode(), ResponseCode.RESPONSE_SUCCESS.getMsg(), pvo);
    }

    @Override
    public R querytagsCount(Integer tagId) {
        if (null == tagId || tagId <= 0) {
            return R.getInstance(ResponseCode.ARG_ERROR.getCode(), ResponseCode.ARG_ERROR.getMsg());
        }
        Integer count = haloPostMapper.querytagsCount(tagId);
        if (null != count) {
            return R.getInstance(ResponseCode.RESPONSE_SUCCESS.getCode(), ResponseCode.RESPONSE_SUCCESS.getMsg(), count);
        }
        return R.getInstance(ResponseCode.INFO_NO_MORE.getCode(), ResponseCode.INFO_NO_MORE.getMsg());
    }

    @Override
    public R selectTag(Integer tagId, Integer page, Integer pageSize) {
        if (null == tagId) {
            return R.getInstance(ResponseCode.ARG_ERROR.getCode(), ResponseCode.ARG_ERROR.getMsg());
        }
        IPage<PostVO> ipg = new Page<>(page, pageSize);
        List<PostVO> pvolist = haloPostMapper.selectTags(tagId, (page - 1) * pageSize, pageSize);
        Integer count = haloPostMapper.querytagsCount(tagId);
        try {
            if (null != pvolist) {
                ipg.setRecords(pvolist)
                        .setCurrent(page)
                        .setSize(pageSize)
                        .setPages(count % pageSize == 0 ? count % pageSize : (count % pageSize) + 1)
                        .setTotal(count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.getInstance(ResponseCode.RESPONSE_SUCCESS.getCode(), ResponseCode.RESPONSE_SUCCESS.getMsg(), ipg);
    }

    public String tagId(String tags) {
        String[] tagArr = tags.split(",");
        StringBuilder sb = new StringBuilder();
        //查询是否含有tag记录,有就返回id，没有就添加到记录中
        for (int i = 0; i < tagArr.length; i++) {
            HaloTag tag = new HaloTag();
            try {
                HaloTag t = tagMapper.selectOne(new QueryWrapper<HaloTag>().eq("tag_name", tagArr[i]));
                if (t != null) {
                    sb.append(t.getTagId() + ",");
                } else {
                    tag.setTagName(tagArr[i]);
                    tagMapper.insertrecord(tag);
                    sb.append(tag.getTagId() + ",");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}
